package com.lz.ub

/**
 * @author you
 * USB command 蓝牙连接的设备
 * @param mac
 * @param w_num 写入的UUID序号
 * @param r_num 读的UUID序号
 * @param isAuto 是否为自动重连
 * @param tag 扩展
 */
class UBCDevice constructor(
    val mac: String,
    val w_num: Int,
    val r_num: Int,
    val isAuto: Boolean = true,
    var tag: Any? = null
) {

    companion object {
        //未连接时的id
        const val INVALID_ID = -1

        //未连接初始化
        const val STATUS_INIT = 0

        //已经发了连接请求可能连接上也可能未连接上
        const val STATUS_CONNECTING = 1

        //已连接,但还没有设置好UUID, 此时的状态会有ID
        const val STATUS_CONNECTED = 2

        //已设置好UUID可服务
        const val STATUS_SERVING = 3
    }

    //连接上时的ID
    var id: Int = INVALID_ID
        private set

    //当前连接状态
    var status: Int = STATUS_INIT
        private set

    //连接指令
    val connectCmd: String get() = if (isAuto) "AT+AUTO_CNT=1,$mac,1\r\n" else "AT+CONNECT=,$mac\r\n"

    //设置UUID指令
    val serviceCmd: String get() = "AT+TRX_CHAN=$id,$w_num,$r_num\r\n"

    //写入指令
    fun writeCmd(size: Int, timeout: Int): String = "AT+SEND=$id,$size,$timeout\r\n"

    //需要连接
    fun needConnected(): Boolean {
        return if (isAuto) status <= STATUS_INIT else status <= STATUS_CONNECTING
    }

    //需要设备服务UUID
    fun needServing(): Boolean = status == STATUS_CONNECTED

    //可以写入,  新蓝牙板由设备设置一次来决定是否可写
    fun mayWrite(): Boolean = status == STATUS_SERVING && id > 0

    fun connecting() {
        status = STATUS_CONNECTING
    }

    //已连接
    fun connected(id: Int) {
        this.id = id
        this.status = STATUS_CONNECTED
    }

    fun serving() {
        status = STATUS_SERVING
    }

    //断开
    fun disconnected() {
        id = -1
        status = if (isAuto) STATUS_CONNECTING else STATUS_INIT
    }

    //重置
    fun reset() {
        id = -1
        status = STATUS_INIT
    }
}